// src/utils/request.js

// 请求基础配置
const BASE_URL = ''; // 基础 API URL
const TIMEOUT = 10000; // 请求超时时间，单位毫秒

// 默认请求头
const HEADER = {
  'Content-Type': 'application/json', // 默认 JSON 请求
};

// 请求队列，用于拦截器
let requestQueue = [];

// 设置请求头
const setRequestHeaders = () => {
  const token = uni.getStorageSync('token');
  if (token) {
    return { Authorization: `Bearer ${token}` };
  }
  return {};
};

// 请求拦截器
const requestInterceptor = () => {
  uni.addInterceptor('request', {
    invoke(options) {
      options.header = {
        ...options.header,
        ...setRequestHeaders(),
      };
      requestQueue.push(options);
      return options;
    },
    success(res) {
      return res;
    },
    fail(err) {
      return err;
    },
  });
};

// 响应拦截器
const responseInterceptor = () => {
  uni.addInterceptor('request', {
    success(res) {
      if (res.statusCode === 200) {
        return res.data;
      } else {
        handleError(res);
        return Promise.reject(res);
      }
    },
    fail(err) {
      uni.showToast({
        title: '网络请求失败',
        icon: 'none',
      });
      return Promise.reject(err);
    },
  });
};

// 错误处理函数
const handleError = (res:any) => {
  if (res.statusCode === 401) {
    uni.showToast({
      title: '身份验证过期，请重新登录',
      icon: 'none',
    });
    uni.removeStorageSync('token');
    uni.redirectTo({
      url: '/pages/login/login',
    });
  } else {
    uni.showToast({
      title: res.data.message || '请求失败',
      icon: 'none',
    });
  }
};

// 封装网络请求
const request = (options:any) => {
  const { url, method = 'GET', data = {}, headers = {} } = options;

  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url, // 基础地址 + 请求路径
      method,
      data,
      header: { ...HEADER, ...headers }, // 合并请求头
      timeout: TIMEOUT, // 设置超时
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data); // 请求成功，返回数据
        } else {
          reject(res); // 请求失败，返回错误信息
        }
      },
      fail: (err) => {
        reject(err); // 网络失败，返回错误信息
      },
    });
  });
};

// 请求重试机制
const retryRequest = (options:any, retries = 3) => {
  return new Promise((resolve, reject) => {
    const attempt = (attemptsLeft:any) => {
      request(options)
        .then(resolve)
        .catch((err) => {
          if (attemptsLeft > 0) {
            console.log(`请求失败，重试中... 剩余重试次数: ${attemptsLeft}`);
            attempt(attemptsLeft - 1); // 重试请求
          } else {
            reject(err); // 达到最大重试次数，返回错误
          }
        });
    };
    attempt(retries); // 发起第一次请求
  });
};

// HTTP 方法封装
const get = (url:any, data = {}, headers = {}) => {
  return request({
    url,
    method: 'GET',
    data,
    headers,
  });
};

const post = (url:any, data = {}, headers = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    headers,
  });
};

const put = (url:any, data = {}, headers = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    headers,
  });
};

const del = (url:any, data = {}, headers = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    headers,
  });
};

// 调用请求拦截器和响应拦截器
requestInterceptor();
responseInterceptor();

// 导出封装的请求方法
export default {
  get,
  post,
  put,
  del,
  retryRequest, // 导出重试请求方法
};
